package com.hst.capacity.infra.persistence.redis;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.hst.capacity.domain.model.entity.auth.TokenEntity;
import com.hst.capacity.domain.repository.redis.TokenRedis;
import com.hst.capacity.infra.util.JJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.time.Instant;
import java.util.concurrent.TimeUnit;

@Repository
public class TokenRedisImpl implements TokenRedis {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void setToken(TokenEntity token) {
        String key = String.format(TOKEN_KEY, token.getAccessToken());
        long expiresTime = token.getExpires() - Instant.now().getEpochSecond();
        try {
            redisTemplate.opsForValue().set(key, JJson.toJsonString(token), expiresTime, TimeUnit.SECONDS);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}
